import React, { useEffect, useState } from "react";
import './proof.css';
import '../../App.css'
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { Toast, Mask, DotLoading } from "antd-mobile";
import { useDispatch } from "react-redux";
import { ProofStepAccount, ProofStepBasic, ProofStepWork, isActionAddressPick, isActionBankPick, isActionDatePick, isActionInput, isActionSelect, isProofContact, isProofFace, isProofFrequentlyUsedApps, isProofMobile } from "@/store/actions/userState";
import { toUnRefApi } from "@/utils/apiUrl";
import FormInput from "@/components/FormInput";
import BankFormSelect from "@/components/BankFormSelect";
import FormSelect from "@/components/FormSelect";
import DateFormSelect from "@/components/DateFormSelect";
import AddressFormSelect from "@/components/AddressFormSelect";
import NgnAddressJson from "../../assets/nigeria_city_list.json"
import { isEmptyString, isMustProofString, toTrimString } from "@/utils/utils";
import { PageTag } from "@/utils/pageTag";
import ProofNavigateBar from "@/components/ProofNavigateBar";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import AddHomeEvent from "@/utils/addHomeEvent";
import PrivacyPolicyLink from "@/components/PrivacyPolicyLink/PrivacyPolicyLink";
import { reqBankCodeList, reqSaveEvent, reqSaveProofData, reqUserState } from "@/store/actions/apiServices";


export default function Proof() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // 获取路由历史 history 对象
    const history = useHistory()

    // 获取路由信息 location 对象
    const location = useLocation()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取显示状态信息
    const [isContactPage, setIsContactPage] = useState(false);
    const [showBankCodeList, setShowBankCodeList] = useState(false);
    const [formatBankCodeInfo, setFormatBankCodeInfo] = useState([[]]);

    //获取Redux Store中的用户状态信息
    const [userStateInfo, setUserStateInfo] = useState({});

    const onReqUserStateCallback = (success, resObj) => {
        setMaskVisible(false);
        if (success && resObj) {
            console.log("Launch-signOrderId: " + resObj.signOrderId);

            //是否为签约中
            const isHomeSigning = isLoanSigning(resObj.signFlag, resObj.signOrderId);
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(resObj.applyStatus);
            //是否为拒绝
            const isHomeReject = isLoanReject(resObj.applyStatus, resObj.orderStatus);
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(resObj.orderStatus);
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(resObj.orderStatus);
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay));
            console.log("Launch-isHomeReviewing: " + isHomeReviewing);
            console.log("Launch-isHomeReject: " + isHomeReject);
            console.log("Launch-isHomeLoaning: " + isHomeLoaning);
            console.log("Launch-isHomeRepay: " + isHomeRepay);
            console.log("Launch-isHomeNotLoan: " + isHomeNotLoan);
            console.log("Launch-isHomeSigning: " + isHomeSigning);

            //跳转状态页
            if (isHomeSigning) {
                history.replace('/guide');
                return;

            } else if (isHomeReviewing) {
                history.replace('/review');
                return;

            } else if (isHomeReject) {
                history.replace('/reject');
                return;

            } else if (isHomeLoaning) {
                history.replace('/loaning');
                return;

            } else if (isHomeRepay) {
                history.replace('/repay');
                return;
            }

            //判断下是否已经做完所有认证
            if (resObj.isProofFinish === true) {
                //跳转申请页
                history.replace('/apply');
                return;
            }

            //是否为号码认证
            if (isProofMobile(resObj.stepTitle)) {
                //跳转申请页
                history.replace('/proofmobile');
                return;
            }

            //是否为常用app认证
            if (isProofFrequentlyUsedApps(resObj.stepTitle)) {
                //跳转申请页
                history.replace('/prooffrequentlyapps');
                return;
            }

            //是否为人脸认证
            if (isProofFace(resObj.stepTitle)) {
                //跳转申请页
                history.replace('/proofface');
                return;
            }

            //是否为联系人认证
            if (isProofContact(resObj.stepTitle)) {
                if (window.isSupportContactPicker === true) {
                    history.replace('/proofcontact');
                } else {
                    history.replace('/proofcontactinput');
                }
                return;
            }

            //是否为联系人页
            const isContactPage = isProofContact(resObj.stepTitle);
            setIsContactPage(isContactPage);

            //是否为绑卡页r
            //const isBankAccountPage = isProofBankAccount(userStateInfo.stepTitle)
            setShowBankCodeList(false);
            setUserStateInfo(resObj);
        }
    };

    //启动时请求首页额度
    useEffect(() => {
        //添加 fb 像素
        // eslint-disable-next-line no-undef
        // fbq('track', 'Page_Proof');
        // eslint-disable-next-line no-undef
        // gtag('track', 'Page_Proof');

        reqSaveEvent("PROOF_START")

        setMaskVisible(true);
        reqUserState(PageTag.PROOF, onReqUserStateCallback);

        return () => {
            reqSaveEvent("PROOF_END")
        }
    }, [])

    const onHandleInputChange = (index, value) => {
        try {
            const newState = { ...userStateInfo };
            const item = newState.dataList[index];
            item.content = value;
            item.realContent = value;
            setUserStateInfo(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleInputChangeForContactExtData = (index, value) => {
        try {
            const newState = { ...userStateInfo };
            const item = newState.extDataList[index];
            item.content = value;
            item.realContent = value;
            setUserStateInfo(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleInputChangeForContact = (parentIndex, index, value) => {
        try {
            const newState = { ...userStateInfo };
            const section = newState.sectionList[parentIndex];
            const item = section[index];
            item.content = value;
            item.realContent = value;
            setUserStateInfo(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleSelectedDataForContactExtData = async (index, type, data) => {
        console.log("onHandleSelectedDataForContactExtData: " + type + ", data: " + data);
        try {
            const newState = { ...userStateInfo };
            const item = newState.extDataList[index];
            item.content = data.label;
            item.realContent = data.value;
            setUserStateInfo(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleSelectedDataForContact = async (parentIndex, index, type, data) => {
        console.log("onHandleSelectedDataForContact: " + type + ", data: " + data);
        try {
            const newState = { ...userStateInfo };
            const section = newState.sectionList[parentIndex];
            const item = section[index];
            item.content = data.label;
            item.realContent = data.value;
            setUserStateInfo(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleSelectedData = async (index, type, data) => {
        console.log("onHandleSelectedDataClick: " + type + ", data: " + data);
        try {
            const newState = { ...userStateInfo };
            const item = newState.dataList[index];
            item.content = data.label;
            item.realContent = data.value;
            setUserStateInfo(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleSelectedAddress = async (index, type, addressList) => {
        console.log("onHandleSelectedAddress: " + type + ", data: " + addressList);
        try {
            const data = addressList.join(" ");
            const newState = { ...userStateInfo };
            const item = newState.dataList[index];
            item.content = data;
            item.realContent = data;

            item.stateContent = addressList[0];
            item.cityContent = addressList[1];
            item.areaContent = addressList[2];
            setUserStateInfo(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleSelectedBankCode = async (index, type, data) => {
        console.log("onHandleSelectedBankCode: " + type + ", data: " + data);
        try {
            const newState = { ...userStateInfo };
            const item = newState.dataList[index];
            item.content = data.label;
            item.realContent = data.value;
            item.bankCodeContent = data.value;
            setUserStateInfo(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleCheckBankCodeList = async (index, type) => {
        console.log("onHandleCheckBankCodeList: " + type);
        checkBankCodeInfo();
    }

    const onHandleCloseBankCodeList = (index, type) => {
        console.log("onHandleCloseBankCodeList: " + index);
        let newState = { ...userStateInfo }
        let item = newState.dataList[index]
        item.show = false;
        setUserStateInfo(newState);
    }

    //失焦监听
    const onHandleBlur = (index, value) => {
        console.log("onHandleBlur: " + index);
    }

    //点击提交
    const onHandleSubmit = () => {
        //组装参数
        const params = {}

        //组装联系人
        if (isProofContact(userStateInfo.stepTitle)) {

            //判断所有内容是否输入完成
            let sectionFinish = true
            userStateInfo.sectionList.forEach(section => {
                section.forEach(item => {
                    if (isMustProofString(item.isMust)) {
                        if (isEmptyString(item.realContent)) {
                            sectionFinish = false
                        }
                    }
                })
            })
            let extFinish = true
            userStateInfo.extDataList.forEach(item => {
                if (isMustProofString(item.isMust)) {
                    if (isEmptyString(item.realContent)) {
                        extFinish = false
                    }
                }
            })

            if ((!sectionFinish) || (!extFinish)) {
                Toast.show("Please fill all contents.")
                return
            }

            const contactList = []
            userStateInfo.sectionList.forEach(section => {
                const contact = {}
                section.forEach(item => {
                    contact[item.paramName] = toTrimString(item.realContent + "")
                })
                contactList.push(contact)
            })
            params["contactList"] = contactList

            //额外字段
            userStateInfo.extDataList.forEach(item => {
                params[item.paramName] = toTrimString(item.realContent + "")
            })

        } else {
            //组装其它页面
            //判断所有内容是否输入完成
            let allFinish = true
            userStateInfo.dataList.forEach(item => {
                if (isMustProofString(item.isMust)) {
                    if (isEmptyString(item.realContent)) {
                        allFinish = false
                    }

                    //判断城市选择字段
                    if (isActionAddressPick(item.action)) {
                        if ((userStateInfo.stepTitle === ProofStepBasic) ||
                            (userStateInfo.stepTitle === ProofStepWork)) {
                            //基本信息 / 工作信息 
                            if (isEmptyString(item.stateContent)) {
                                allFinish = false
                            }
                            if (isEmptyString(item.cityContent)) {
                                allFinish = false
                            }
                            if (isEmptyString(item.areaContent)) {
                                allFinish = false
                            }
                        }
                    }

                    //判断银行选择字段
                    if (isActionBankPick(item.action)) {
                        if (userStateInfo.stepTitle === ProofStepAccount) {
                            //绑卡信息 
                            if (isEmptyString(item.bankCodeContent)) {
                                allFinish = false
                            }
                        }
                    }
                }
            })

            if ((!allFinish)) {
                Toast.show("Please fill all contents.")
                return
            }

            userStateInfo.dataList.forEach(item => {
                params[item.paramName] = toTrimString(item.realContent + "")

                //判断城市选择字段
                if (isActionAddressPick(item.action)) {
                    if ((userStateInfo.stepTitle === ProofStepBasic) ||
                        (userStateInfo.stepTitle === ProofStepWork)) {
                        //基本信息 / 工作信息 
                        params[item.paramNameState] = toTrimString(item.stateContent + "")
                        params[item.paramNameCity] = toTrimString(item.cityContent + "")
                        params[item.paramNameArea] = toTrimString(item.areaContent + "")
                    }
                }

                //判断银行选择字段
                if (isActionBankPick(item.action)) {
                    if (userStateInfo.stepTitle === ProofStepAccount) {
                        //绑卡信息 
                        params[item.paramNameBankCode] = toTrimString(item.bankCodeContent + "")
                    }
                }
            });
        }
        console.log(params)

        //显示loading
        setMaskVisible(true)

        //保存认证api
        const api = toUnRefApi(userStateInfo.apiUrl)
        console.log(api)

        //获取Action
        reqSaveProofData(api, params, userStateInfo.stepTitle, (success, resObj) => {
            if (success) {
                reqUserState(PageTag.PROOF, onReqUserStateCallback);
            }
        });
    }

    const onHandleNavGoBack = () => {
        history.goBack()
    }

    const checkBankCodeInfo = () => {
        console.log("Proof-checkBankCodeInfo: ");
        try {
            let isArray = Array.isArray(formatBankCodeInfo)
            if (!isArray || (formatBankCodeInfo.length === 0)) {
                setMaskVisible(false);
                reqBankCodeList((success, resObj) => {
                    setMaskVisible(false);
                    if (success) {
                        setFormatBankCodeInfo(resObj);
                    }
                });
            }
        } catch (e) {
            console.log(e)
        }
    }

    const onHandleAddToHome = (type) => {
        console.log(`点击add home监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    const onHandleAddToHomeClose = () => {
        console.log(`点击close add home监听`)
        setAddHomeMaskVisible(false)
    }


    return (
        <div className="proofRoot">
            <ProofNavigateBar theme="white" onBackClick={onHandleNavGoBack} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{userStateInfo.pageTitle}</ProofNavigateBar>
            <div className="proofContent">
                {/* 联系人-额外输入 */}
                {isContactPage && userStateInfo.extDataList && userStateInfo.extDataList.map((value, index) => {
                    return (
                        <div className="proofItemList" key={index}>
                            {(isActionSelect(value.action) === true) && <FormSelect
                                placeholder={value.hint}
                                value={value.content}
                                title={value.title}
                                list={value.pickValues}
                                onSelectedDataClick={e => { onHandleSelectedDataForContactExtData(index, value.paramName, e) }}
                                autoComplete="off" />}

                            {(isActionInput(value.action) === true) && <FormInput
                                placeholder={value.hint}
                                value={value.content}
                                title={value.title}
                                onBlur={e => { onHandleBlur(index, e.target.value) }}
                                onChange={e => { onHandleInputChangeForContactExtData(index, e) }}
                                autoComplete="off" />}
                        </div>
                    )
                })}
                {/* 联系人-常量 */}
                {isContactPage && userStateInfo.sectionList && userStateInfo.sectionList.map((value, index) => {
                    return (
                        <div className="contentColumnStart" key={index}>
                            <div className="proofEdgeTopWhite"></div>
                            <div className="proofEdgeTopMainBackground"></div>
                            {(value.map((itemValue, itemIndex) => {
                                return (
                                    <div className="proofItemList" key={index + "_" + itemIndex}>
                                        {(isActionSelect(itemValue.action) === true) && <FormSelect
                                            placeholder={itemValue.hint}
                                            value={itemValue.content}
                                            title={itemValue.title}
                                            list={itemValue.pickValues}
                                            onSelectedDataClick={e => { onHandleSelectedDataForContact(index, itemIndex, itemValue.paramName, e) }}
                                            autoComplete="off" />}

                                        {(isActionInput(itemValue.action) === true) && <FormInput
                                            placeholder={itemValue.hint}
                                            value={itemValue.content}
                                            title={itemValue.title}
                                            onBlur={e => { onHandleBlur(itemIndex, e.target.value) }}
                                            onChange={e => { onHandleInputChangeForContact(index, itemIndex, e) }}
                                            autoComplete="off" />}
                                    </div>
                                )
                            }))}
                        </div>
                    )
                })}

                {/* 其它 */}
                {(!isContactPage) && userStateInfo.dataList && userStateInfo.dataList.map((value, index) => {
                    return (
                        <div className="proofItemList" key={index}>

                            {(isActionSelect(value.action) === true) && <FormSelect
                                placeholder={value.hint}
                                value={value.content}
                                title={value.title}
                                list={value.pickValues}
                                onBlur={e => { onHandleBlur(index, e.target.value) }}
                                onChange={e => { onHandleInputChange(index, e) }}
                                onSelectedDataClick={e => { onHandleSelectedData(index, value.paramName, e) }}
                                autoComplete="off" />}

                            {(isActionInput(value.action) === true) && <FormInput
                                placeholder={value.hint}
                                value={value.content}
                                title={value.title}
                                onBlur={e => { onHandleBlur(index, e.target.value) }}
                                onChange={e => { onHandleInputChange(index, e) }}
                                autoComplete="off" />}

                            {(isActionAddressPick(value.action) === true) && <AddressFormSelect
                                placeholder={value.hint}
                                value={value.content}
                                title={value.title}
                                list={NgnAddressJson}
                                onChange={e => { onHandleInputChange(index, e) }}
                                onSelectedDataClick={e => { onHandleSelectedAddress(index, value.paramName, e) }}
                                autoComplete="off" />}

                            {(isActionDatePick(value.action) === true) && <DateFormSelect
                                placeholder={value.hint}
                                value={value.content}
                                title={value.title}
                                showDatePicker={value.show}
                                onChange={e => { onHandleInputChange(index, e) }}
                                onSelectedDataClick={e => { onHandleSelectedData(index, value.paramName, e) }}
                                autoComplete="off" />}

                            {(isActionBankPick(value.action) === true) && <BankFormSelect
                                placeholder={value.hint}
                                value={value.content}
                                title={value.title}
                                showPicker={showBankCodeList}
                                list={formatBankCodeInfo}
                                onCloseClick={e => { onHandleCloseBankCodeList(index, value.paramName) }}
                                onCheckDataClick={e => { onHandleCheckBankCodeList(index, value.paramName) }}
                                onSelectedDataClick={e => { onHandleSelectedBankCode(index, value.paramName, e) }}
                                autoComplete="off" />}
                        </div>
                    )
                })}
            </div>

            <div className="proofApplyBtn" onClick={onHandleSubmit}>
                <div className="mainButtonGradient">Next</div>
            </div>

            {/* privacy policy */}
            <PrivacyPolicyLink pageTag={userStateInfo.pageTitle} showCheckbox={false} linkText="Privacy policy" />

            {/* </div> */}
            {/* add home gif dialog */}
            {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}